<?php

/**
 * 夏日葵电商系统
 * http://www.xiarikui.com
 */

namespace Admin\Controller;

use Org\Apply\InstallAndUninstall\InstallAndUnInstallApply;
use Org\Menu\Menu;

class ApplicationController extends BaseController {

    public $apply;

    public function _initialize() {
        parent::_initialize();
        //  更新应用
        $this->insertApplication($this->scanApplication());

        $this->apply = new InstallAndUnInstallApply();
    }

    /**
     * 应用页面
     */
    public function index() {
        $application_list = M('application')->select();
        $this->assign('list', $application_list);
        $this->display();
    }

    /**
     * 应用安装卸载
     */
    public function install() {
        $condition['code'] = I('get.code');
        $install['status'] = I('get.install');

        if(!$this->apply->isEdit()) {
            $info['status'] = 0;
            $info['msg'] = 'ApplicationController.class.php 文件被修改过,不能安装';
            exit(json_encode($info));
        }
        if ($install['status'] == 1) { // 安装
            $info = $this->apply->installApply($condition['code']);
        } else { // 卸载
            $info = $this->apply->unInstallApply($condition['code']); // 执行应用卸载代码
        }
        exit(json_encode($info));
    }

    /**
     * 应用信息配置
     */
    public function setting() {
        $condition['code'] = I('get.code');

        $model = M('application');
        $row = $model->where($condition)->find();
        if (!$row) {
            exit($this->error("不存在该应用"));
        }

        $row['config'] = unserialize($row['config']);

        if (IS_POST) {
            $config = I('post.config');
            //空格过滤
            $config = trim_array_element($config);
            if ($config) {
                $config = serialize($config);
            }
            $row = $model->where($condition)->save(array('config_value' => $config));
            if ($row) {
                exit($this->success("操作成功"));
            }
            exit($this->error("操作失败"));
        }

        $this->assign('application', $row);
        $this->assign('config_value', unserialize($row['config_value']));

        $this->display();
    }

    /**
     * 检查应用是否存在
     * @return mixed
     */
    private function checkExist() {
        $condition['code'] = I('get.code');

        $model = M('application');
        $row = $model->where($condition)->find();
        if (!$row && false) {
            exit($this->error("不存在该应用"));
        }
        return $row;
    }

    /**
     * 应用目录扫描
     * @return array 返回目录数组
     */
    private function scanApplication() {
        $application_list = array();
        $application_list = $this->dirscan(C('APPLICATION_PATH'));
        foreach ($application_list as $k => $v) {
            if (!file_exists(C('APPLICATION_PATH') . $v . '/config.php'))
                unset($application_list[$k]);
            else {
                $application_list[$k] = include(C('APPLICATION_PATH') . $v . '/config.php');
            }
        }
        return $application_list;
    }

    /**
     * 获取应用目录列表
     * @param $dir
     * @return array
     */
    private function dirscan($dir) {
        $dirArray = array();
        if (false != ($handle = opendir($dir))) {
            $i = 0;
            while (false !== ($file = readdir($handle))) {
                //去掉"“.”、“..”以及带“.xxx”后缀的文件
                if ($file != "." && $file != ".." && !strpos($file, ".")) {
                    $dirArray[$i] = $file;
                    $i++;
                }
            }
            //关闭句柄
            closedir($handle);
        }
        return $dirArray;
    }

    /**
     * 更新应用到数据库
     * @param $application_list 本地应用数组
     */
    private function insertApplication($application_list) {
        $applicationRs = M('application')->field('code')->select();
        $arr = array();
        foreach ($application_list as $k => $v) {
            $tmp['code'] = $v['code'];
            $arr[] = $tmp;
            $is_exit = M('application')->where(array('code' => $v['code']))->find();
            if (empty($is_exit)) {
                $add['code'] = $v['code'];
                $add['name'] = $v['name'];
                $add['version'] = $v['version'];
                $add['icon'] = $v['icon'];
                $add['author'] = $v['author'];
                $add['desc'] = $v['desc'];
                $add['bank_code'] = serialize($v['bank_code']);
                $add['scene'] = $v['scene'];
                $add['config'] = serialize($v['config']);
                M('application')->add($add);
            }
        }
        foreach ($applicationRs as $k => $v) {
            if (!in_array($v, $arr)) {
                M('application')->where($v)->delete();
            }
        }
    }


}
